<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\User;

use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Logger\LoggerFactory;

/**
 * @AutoController()
 * 这是user 模块下的say控制器的index方法
 */
class SayController extends AbstractController
{

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    public function __construct(LoggerFactory $loggerFactory)
    {
        parent::__construct();
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function index()
    {
        $user = $this->request->input('user', 'user Hyperf');
        $method = $this->request->getMethod();
        $start_time = time();
        $this->dosomething();
        $this->dosomething1();
        $this->dosomething2();
        $end_time = time();
        echo '执行时间为：' . ($end_time - $start_time) . 's' . PHP_EOL;
        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }

    // co协程异步非阻塞函数测试
    public function test()
    {
        $user = $this->request->input('user', 'co Hyperf');
        $method = $this->request->getMethod();

        $start_time = time();
        co(function () {
            $this->dosomething();
            $this->dosomething1();
            $this->dosomething2();
        });
        $end_time = time();
        echo '执行时间为：' . ($end_time - $start_time) . 's' . PHP_EOL;

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }

    public function dosomething()
    {
        // 模拟发送短信
        sleep(1);
        $this->logger->info("i am do sonthing");

    }

    public function dosomething1()
    {
        // 模拟发送邮件
        sleep(1);
        $this->logger->info("i am do sonthing1");

    }

    public function dosomething2()
    {
        // 模拟同步用户消息到其它系统
        sleep(2);
        $this->logger->info("i am do sonthing2");

    }
}
